//
//  ByUIScanCodeVC.m
//  chequanbao_ios
//
//  Created by mc on 2017/5/9.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIScanCodeVC.h"

#import <AVFoundation/AVFoundation.h>

// view
#import "MaskView.h"

// vc
#import "ByUIShopsDetailVC.h"

@interface ByUIScanCodeVC ()<AVCaptureMetadataOutputObjectsDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) AVCaptureSession *session;

@property (nonatomic, assign) BOOL flashOpen;
@end

@implementation ByUIScanCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *bgImg = [self.view viewWithTag:888];
    [bgImg removeFromSuperview];
    
    [self addLeftBackBarButtonItem];
    [self createViewAndLayer];
    [self addBYItemviews:@[@"闪光灯",@"相册"] mode:ByNavigationItemModeText position:ByNavigationItemPositionModeRight];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.session startRunning];
    
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.session stopRunning];
}

-(void)rightItemsAction:(NSInteger)rightIndex{
    if (rightIndex == 0) {
        [self openflash];
    }else{
        // 1.判断相册是否可以打开
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
        // 2. 创建图片选择控制器
        UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        
        ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        // 4.设置代理
        ipc.delegate = self;
        
        // 5.modal出这个控制器
        [self presentViewController:ipc animated:YES completion:nil];

    }
    
}

#pragma mark - 创建视图以及图层
- (void)createViewAndLayer{
    MaskView *maskView = [[MaskView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:maskView];
    [maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(@0);
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(@0);
        }
    }];
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
}
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0)
    {
        
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects firstObject];
        NSString *resultStr = metadataObject.stringValue;
        // 判断是否是商家 若是商家直接跳商家详情
        if ([resultStr containsString:@"seller_id"]) {
            [self.session stopRunning];
            ByUIShopsDetailVC *vc = [[ByUIShopsDetailVC alloc] init];
            NSRange start = [resultStr rangeOfString:@"seller_id/"];
            NSRange end = [resultStr rangeOfString:@".html"];
            NSString *seller_id = [resultStr substringWithRange:NSMakeRange(start.location + start.length, end.location - start.location - start.length)];
            vc.type = seller_id;
            [self by_normalPush:vc hasNavi:YES];

        }
        // 用户(则直接提示)
        else if([resultStr containsString:@"uid"]){
            [ByCoreToolAlert showOnlyText:@"这是普通用户"];
        }
    
        NSLog(@"%@",metadataObject.stringValue);
        
        
        
//        ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:@"https://www.baidu.com"];
//        [self by_normalPush:vc hasNavi:YES];
//        [ByCoreToolAlert showOnlyText:metadataObject.stringValue];
//        [self showAlertWithTitle:@"扫描结果" message:metadataObject.stringValue handler:^(UIAlertAction *action) {
//            [self.session startRunning];
//        }];
    }
}

#pragma mark - 开关闪光灯
- (void)openflash
{
    self.flashOpen = !self.flashOpen;
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    if ([device hasTorch] && [device hasFlash])
    {
        [device lockForConfiguration:nil];
        
        if (self.flashOpen)
        {
//            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭闪光灯" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonDidClick:)];
//
            device.torchMode = AVCaptureTorchModeOn;
            device.flashMode = AVCaptureFlashModeOn;
        }
        else
        {
//            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"打开闪光灯" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonDidClick:)];
            
            device.torchMode = AVCaptureTorchModeOff;
            device.flashMode = AVCaptureFlashModeOff;
        }
        
        [device unlockForConfiguration];
    }
}
#pragma mark -------- UIImagePickerControllerDelegate---------
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // 1.取出选中的图片
    UIImage *pickImage = info[UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImagePNGRepresentation(pickImage);
    
    CIImage *ciImage = [CIImage imageWithData:imageData];
    
    // 2.从选中的图片中读取二维码数据
    // 2.1创建一个探测器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
    
    // 2.2利用探测器探测数据
    NSArray *feature = [detector featuresInImage:ciImage];
    
    // 2.3取出探测到的数据
    for (CIQRCodeFeature *result in feature) {
        NSString *resultStr = result.messageString;
        // 判断是否是商家 若是商家直接跳商家详情
        if ([resultStr containsString:@"seller_id"]) {
            ByUIShopsDetailVC *vc = [[ByUIShopsDetailVC alloc] init];
            NSRange start = [resultStr rangeOfString:@"seller_id/"];
            NSRange end = [resultStr rangeOfString:@".html"];
            NSString *seller_id = [resultStr substringWithRange:NSMakeRange(start.location + start.length, end.location - start.location - start.length)];
            vc.type = seller_id;
            [self by_normalPush:vc hasNavi:YES];
        }
        // 用户(则直接提示)
        else if([resultStr containsString:@"uid"]){
            [ByCoreToolAlert showOnlyText:@"这是普通用户"];
        }

//        [ByCoreToolAlert showOnlyText:result.messageString];
//        NSString *urlStr = result.messageString;
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        
//        ByWebViewController *vc = [[ByWebViewController alloc] initWithTotalUrlString:@"https://www.baidu.com"];
//        [self by_normalPush:vc hasNavi:YES];
    }
    
    // 注意: 如果实现了该方法, 当选中一张图片时系统就不会自动关闭相册控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Getter
- (AVCaptureSession *)session
{
    if (!_session)
    {
        _session = ({
            //获取摄像设备
            AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
            //创建输入流
            AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
            if (!input)
            {
                return nil;
            }
            
            //创建输出流
            AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
            //设置代理 在主线程里刷新
            [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
            //设置扫描区域的比例
            CGFloat width = 300 / CGRectGetHeight(self.view.frame);
            CGFloat height = 300 / CGRectGetWidth(self.view.frame);
            output.rectOfInterest = CGRectMake((1 - width) / 2, (1- height) / 2, width, height);
            
            AVCaptureSession *session = [[AVCaptureSession alloc] init];
            //高质量采集率
            [session setSessionPreset:AVCaptureSessionPresetHigh];
            [session addInput:input];
            [session addOutput:output];
            
            //设置扫码支持的编码格式(这里设置条形码和二维码兼容)
            output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,
                                           AVMetadataObjectTypeEAN13Code,
                                           AVMetadataObjectTypeEAN8Code,
                                           AVMetadataObjectTypeCode128Code];
            
            session;
        });
    }
    
    return _session;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
